﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace LBCMS.BLL
{
    public static class PredicateBuilder
    {
        public static Expression<Func<T, bool>> True<T>()
        {
            return f => true;
        }

        public static Expression<Func<T, bool>> False<T>()
        {
            return f => false;
        }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                            Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                             Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
        }

        public class queryCondition
        {
            public List<queryItem> and { get; set; }
            public List<queryItem> or { get; set; }
        }

         

        public class queryItem
        {
            public string paraName { get; set; }
            public string paraValue { get; set; }

            public string paraOprator { get; set; }
        }
        public class QueryModelBinder : DefaultModelBinder
        {
            public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                var request = controllerContext.HttpContext.Request;
                var valueShouldFilter = bindingContext.ModelMetadata.DataTypeName;

                var resultProvider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (resultProvider != null)
                {
                    string result = resultProvider.AttemptedValue;

                    return Helper.JsonHelper.toObj<queryCondition>(result);
                }
                else
                {
                    return new queryCondition();
                }

                //base.BindModel(controllerContext, bindingContext);
            }
        }
    }

    

}